package com.example.im.inform

import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.support.v4.app.NotificationCompat
import android.text.TextUtils
import cc.vv.lkbasecomponent.util.LKStringUtil
import cc.vv.lkimcomponent.lkim.bean.LKIMMessage
import cc.vv.lkimcomponent.lkim.bean.body.LKIMTxtBody
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMChatType
import com.example.BaseNewApplication
import com.example.baselibrary.R
import com.example.baselibrary.db.dao.AccountDao
import com.example.baselibrary.db.dao.DNDDao
import com.example.baselibrary.db.dao.GroupDao
import com.example.baselibrary.util.LKAppUtil
import com.example.baselibrary.util.LKSystemHardUtil
import com.example.util.finallist.IMExtKey
import com.example.util.finallist.SkKey
import java.util.*

/**
 * IM通知类
 * @author  chaohaipeng  on 2018/7/23.
 */
class InformOperate {
    private val CCP_NOTIFICATOIN_ID_CALLING = 0x1
     val mContext = BaseNewApplication.getInstance()
    private var mNotificationManager: NotificationManager? = null
    private val mUserAndId = HashMap<String, Int>()//消息发送者,和其对应的提示ID
    private val mUserAndMsgNum = HashMap<String, Int>()//消息发送者,和其对应的消息条数


    private object mHolder {
        val mContext = BaseNewApplication.getInstance()
        val instance = InformOperate(initnotify())
        private fun initnotify(): NotificationManager {
            return  mContext?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        }
    }
   constructor(notificationManager: NotificationManager){
       mNotificationManager= notificationManager
   }
    companion object {

        fun getInstance(): InformOperate {

            return mHolder.instance
        }
    }
    /**
     * 创建IM消息通知
     *
     * @param lkimMessage 消息体
     */
    @Synchronized
    fun createIMInform(lkimMessage: LKIMMessage) {
        if (LKIMChatType.GroupChat == lkimMessage.lkimChatType) {
            val dndTable = DNDDao.getInstance().queryById(lkimMessage.toAccount)
            if (null != dndTable) {
                return
            }
        }
        LKSystemHardUtil.getInstance().vibrateAndPlayTone(mContext, true, true)
        val isForeground = LKAppUtil.getInstance().isForeground(mContext)
        if (isForeground) return
        var content: String
        val messageType = Integer.valueOf(lkimMessage.getAttribute(IMExtKey.EXTKEY_MESSAGETYPE, SkKey.BTKEY_String_1))!!
        when (messageType) {
            SkKey.BTKEY_INT_1 -> {
                val lkimTxtBody = lkimMessage.lkIMBody as LKIMTxtBody
                content = lkimTxtBody.message
            }
            SkKey.BTKEY_INT_2 -> content = LKStringUtil.getString(R.string.string_imbody_voice)
            SkKey.BTKEY_INT_3 -> content = LKStringUtil.getString(R.string.string_imbody_image)
            SkKey.BTKEY_INT_4 -> content = LKStringUtil.getString(R.string.string_imbody_link)
            SkKey.BTKEY_INT_5 -> content = LKStringUtil.getString(R.string.string_imbody_video)
            else -> content = " "
        }
        if (LKIMChatType.GroupChat == lkimMessage.lkimChatType) {
            val dndTable = DNDDao.getInstance().queryById(lkimMessage.toAccount)
            if (null != dndTable) {
                return
            }
            val accountTable = AccountDao.getInstance().queryById(lkimMessage.fromAccount)
            content = String.format(Locale.CHINESE, "%s：%s", accountTable.nick, content)
            createInform(content, SkKey.BTKEY_INT_0, lkimMessage.toAccount, lkimMessage.fromAccount)
        } else if (LKIMChatType.SingleChat == lkimMessage.lkimChatType) {
            createInform(content, SkKey.BTKEY_INT_0, lkimMessage.fromAccount)
        }
    }


    /**
     * 创建密聊通知
     *
     * @param lkimMessage
     */
    @Synchronized
    fun createSecurityIMInform(lkimMessage: LKIMMessage) {
        LKSystemHardUtil.getInstance().vibrateAndPlayTone(mContext, true, true)
        val isForeground = LKAppUtil.getInstance().isForeground(mContext)
        if (isForeground) return
        createInform("", SkKey.BTKEY_INT_1, lkimMessage.fromAccount)
    }

    /**
     * 创建通知栏提醒
     *
     * @param content
     * @param informType    0:IM消息 1:密聊
     * @param conversionIds
     */
    @Synchronized private fun createInform(content: String, informType: Int, vararg conversionIds: String) {
        if (null == conversionIds || conversionIds.size == 0) {
            return
        }
        var notifyId = 10000
        if (mUserAndId.containsKey(conversionIds[0])) {
            notifyId = mUserAndId.get(conversionIds[0])!!
        } else {
            val ite = mUserAndId.keys.iterator()
            while (ite.hasNext()) {
                val key = ite.next() as String   //   key
                if (notifyId < mUserAndId.get(key)!!) {
                    notifyId = mUserAndId.get(key)!!
                }
            }
            notifyId++
            mUserAndId.put(conversionIds[0], notifyId)
        }
        val isHasUserId = mUserAndMsgNum.containsKey(conversionIds[0])
        var msgNum = 1
        if (isHasUserId) {
            msgNum += mUserAndMsgNum.get(conversionIds[0])!!
        }
        mUserAndMsgNum.put(conversionIds[0], msgNum)
        sendNotification(notifyId, content, informType, msgNum, *conversionIds)
    }

    /**
     * 发送通知
     *
     * @param notifyId
     * @param content
     * @param informType
     * @param msgNum
     * @param conversionIds
     */
    private fun sendNotification(notifyId: Int, content: String, informType: Int, msgNum: Int, vararg conversionIds: String) {
        try {
//            val intent = Intent(mContext,AppMainTableActivity::class.java)
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
//            val titleAndMsg = initMsgContent(content, informType, msgNum, intent, *conversionIds)
//            val mBuilder = NotificationCompat.Builder(mContext)
//                    .setSmallIcon(mContext?.getApplicationInfo()?.icon!!)
//                    .setWhen(System.currentTimeMillis())
//                    .setAutoCancel(true)
//            val pendingIntent = PendingIntent.getActivity(mContext, notifyId, intent, PendingIntent.FLAG_UPDATE_CURRENT)
//            mBuilder.setContentTitle(titleAndMsg[0])//标题
//            mBuilder.setContentText(titleAndMsg[1])//显示文本
//            mBuilder.setContentIntent(pendingIntent)//需要跳转的
//            val notification = mBuilder.build()
//            mNotificationManager?.notify(notifyId, notification)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    /**
     * 初始化标题、显示内容
     *
     * @param content
     * @param informType
     * @param msgNum
     * @param intent
     * @param conversionIds
     * @return
     */
    private fun initMsgContent(content: String, informType: Int, msgNum: Int, intent: Intent, vararg conversionIds: String): Array<String> {
        var notifyTitle = ""
        var notifyContent = ""
        if (null != conversionIds) {
            when (informType) {
                SkKey.BTKEY_INT_0 -> {
                    if (conversionIds.size > 1) {
                        val groupTable = GroupDao.getInstance().queryById(conversionIds[0])
                        notifyTitle = groupTable.groupNick
                    } else {
                        val accountTable = AccountDao.getInstance().queryById(conversionIds[0])
                        notifyTitle = accountTable.nick
                    }
                    if (TextUtils.isEmpty(notifyTitle)) {
                        notifyTitle = mContext?.getPackageManager()?.getApplicationLabel(mContext.getApplicationInfo()).toString()
                    }
                    if (msgNum > 1) {
                        notifyTitle = String.format("%1\$s (%2\$d条新消息)", notifyTitle, msgNum)
                    }
                    notifyContent = content
//                    intent.putExtra(BTParamKey.KEY_PUSH_TYPE, SkKey.BTKEY_INT_0)
                }
            }
        }
        return arrayOf(notifyTitle, notifyContent)
    }

    /**
     * 重置通知栏通知提示
     */
    fun reset() {
        if (mNotificationManager != null) {
            val entries = mUserAndId.entries
            val iterator = entries.iterator()
            while (iterator.hasNext()) {
                val next = iterator.next()
                val notifyId = next.value
                if (notifyId != CCP_NOTIFICATOIN_ID_CALLING) {
                    mNotificationManager?.cancel(notifyId!!)
                }
            }
        }
        mUserAndId.clear()
        mUserAndMsgNum.clear()
    }


}